package com.tyf.bookreader.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tyf.bookreader.constant.RedisConstants;
import com.tyf.bookreader.domain.BrBook;
import com.tyf.bookreader.domain.BrCategory;
import com.tyf.bookreader.dto.BookCategoryDto;
import com.tyf.bookreader.mapper.BrBookMapper;
import com.tyf.bookreader.mapper.BrCategoryMapper;
import com.tyf.bookreader.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Description TODO
 * @Author shallow
 * @Date 2023/4/2 10:02
 */

@Component
public class BookCategoryCacheManager {

    @Autowired
    private BrCategoryMapper categoryMapper;
    @Autowired
    private RedisService redisService;

    @Autowired
    private BrBookMapper bookMapper;

    public List<BookCategoryDto> listCategory(){
        List<BookCategoryDto> bookCategoryList;
        //检查缓存是否有内容
        if (redisService.lSize(RedisConstants.BOOK_CATEGORY_LIST_CACHE_KEY) == 0) {
            bookCategoryList =categoryMapper.selectList(new LambdaQueryWrapper<BrCategory>().eq(BrCategory::getDeleted,0))
                    .stream().map(v ->{
                        BookCategoryDto bookCategoryDto = BookCategoryDto.builder()
                                .id(v.getId())
                                .name(v.getCategoryName())
                                .build();
                        redisService.lPush(RedisConstants.BOOK_CATEGORY_LIST_CACHE_KEY,bookCategoryDto,RedisConstants.COMMON_CACHE_TIME);
                        return bookCategoryDto;
                    }).toList();
            return bookCategoryList;
        }
        return redisService.lRange(RedisConstants.BOOK_CATEGORY_LIST_CACHE_KEY,0,-1)
                .stream()
                .map(v-> BeanUtil.toBean(v,BookCategoryDto.class))
                .toList();
    }

    /**
     * 获得最近更新的本类别的500本小说，缓存30分钟
     */
    public List<Long> getLastUpdateList(Long categoryId){
        if(redisService.lSize(RedisConstants.CATEGORY_LAST_UPDATE_CACHE_KEY)!=0){
            List<Integer> idList = redisService.lRange(RedisConstants.CATEGORY_LAST_UPDATE_CACHE_KEY, 0, -1).stream().map(v->(Integer)v).toList();
//
            return idList.stream().map(v->v.longValue()).toList();
        }
        List<Long> bookIdList = bookMapper.selectList(new LambdaQueryWrapper<BrBook>()
                .eq(BrBook::getCategoryId, categoryId)
                .eq(BrBook::getDeleted, 0)
                .orderByDesc(BrBook::getUpdateTime)
                .last("limit 500")).stream().map(v->{
                    redisService.lPush(RedisConstants.CATEGORY_LAST_UPDATE_CACHE_KEY,v.getId(),RedisConstants.COMMON_CACHE_TIME);
                    return v.getId();
        }).toList();
        return bookIdList;
    }
}
